package com.exam.aop;


import com.exam.context.UserUtils;
import com.exam.entity.ExitForm;
import com.exam.entity.LogTable;
import com.exam.entity.Login;
import com.exam.entity.dto.ForgotDto;
import com.exam.entity.dto.RegisterDto;
import com.exam.teacher.mapper.OperateLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;

@Slf4j
@Component
@Order(2)
@Aspect // aop类
public class LogAspect implements WebMvcConfigurer {

    @Autowired
    private OperateLogMapper operateLogMapper;

    @Autowired
    private HttpServletRequest request;

    //    切入点表达式
    @Around("@annotation(com.exam.anno.MyLog)")
    public Object recordLog(ProceedingJoinPoint joinPoint) throws Throwable {


        Object result = joinPoint.proceed();
        //1、从请求头中获取令牌
        String userId = "";

        Object[] args = joinPoint.getArgs();

        if (args[0].getClass().toString().equals("class com.exam.entity.Login")) {
            Login login = (Login) args[0];
            userId = login.getUsername();
        } else if (args[0].getClass().toString().equals("class com.exam.entity.dto.ForgotDto")) {
            ForgotDto login = (ForgotDto) args[0];
            if (login.getStudentName() != null) {
                userId = String.valueOf(login.getStudentName());
            } else {
                userId = String.valueOf(login.getTeacherName());
            }
        } else if (args[0].getClass().toString().equals("class com.exam.entity.dto.RegisterDto")) {
            RegisterDto login = (RegisterDto) args[0];
            if (login.getStudentId() != null) {
                userId = String.valueOf(login.getStudentId());
            } else {
                userId = String.valueOf(login.getTeacherId());
            }
        } else if (args[0].getClass().toString().equals("class com.exam.entity.ExitForm")) {
            ExitForm login = (ExitForm) args[0];
            if (login.getUserId() != null) {
                userId = login.getUserId();
            }
        }
        else {
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
//                    System.out.println(cookie.getName() + "--------" + URLDecoder.decode(cookie.getValue(), StandardCharsets.UTF_8.toString()));
                    if (cookie.getName().equals("userId")) {
                        userId = cookie.getValue();
                    }
                }
            }
        }


        Date timestamp = new Date();

        String userAgent = parseUserAgent(request.getHeader("User-Agent"));
        String ipAddress = request.getRemoteAddr();
        String requestParams = request.getRequestURI();
        String method = request.getMethod();

//        System.out.println("userId: " + userId);
//        System.out.println("timestamp: " + timestamp);
//        System.out.println("ipAddress: " + ipAddress);
//        System.out.println("userAgent: " + userAgent);
//        System.out.println("requestParams: " + requestParams);
//        System.out.println("method：" + method);

        LogTable logTable = new LogTable();
        logTable.setUserId(userId);
        logTable.setTimestamp(timestamp);
        logTable.setIpAddress(ipAddress);
        logTable.setUserAgent(userAgent);
        logTable.setRequestParams(requestParams);
        logTable.setMethod(method);

        operateLogMapper.insertStudent(logTable);

        return result;

    }

    private String parseUserAgent(String userAgent) {

        if (userAgent != null) {
            if (userAgent.contains("MSIE")) {
                return "Internet Explorer";
            } else if (userAgent.contains("Firefox")) {
                return "Firefox";
            } else if (userAgent.contains("Chrome")) {
                return "Chrome";
            } else if (userAgent.contains("Safari")) {
                return "Safari";
            } else {
                return "Unknown";
            }
        } else {
            return "Unknown";
        }

    }

}
